<template>
  <div>
    <!-- Breadcrumb面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- Card卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!--  -->

    <!-- 角色列表区 -->
    <el-table :data="roleList" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="prop">
          <el-row
            :class="['bottomBorder', index1 == 0 ? 'topBorder' : '', 'vcenter']"
            v-for="(item1, index1) in prop.row.children"
            :key="item1.id"
          >
            <!-- 一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightsById(prop.row, item1.id)">
                {{ item1.authName }}
              </el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!--二级和三级权限 -->
            <el-col :span="19">
              <el-row
                :class="[index2 == 0 ? '' : 'topBorder', 'vcenter']"
                v-for="(item2, index2) in item1.children"
                :key="item2.id"
              >
                <!-- 二级 占6列 -->
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="removeRightsById(prop.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级 占18列 -->
                <el-col :span="18">
                  <el-tag
                    type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    closable
                    @close="removeRightsById(prop.row, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!-- <pre>
            {{ prop.row }}
          </pre>-->
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="prop">
          <!-- <span v-show="false">{{ prop.row }}</span> -->
          <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
          <el-button
            @click="showSetRightDialog(prop.row)"
            type="warning"
            size="mini"
            icon="el-icon-setting"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightsClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 分配权限弹窗
      setRightDialogVisible: false,
      // 所有权限列表数据
      rightsList: [],
      // 树形控件属性
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认勾选的节点id值
      defKeys: [],
      // 保存角色id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      // 成功
      this.roleList = res.data
    },
    async removeRightsById(role, rightid) {
      // console.log(role)
      // 点确定返回'confirm' ,点取消返回'cancel'必须用catch()
      const isConfirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(isConfirm)
      if (isConfirm !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightid}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // console.log(res)
      role.children = res.data
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rightsList = res.data
      // 执行获取默认权限让树的复选框默认勾选
      this.getDefKeys(role, this.defKeys)
      // 展示分配权限弹出框
      this.setRightDialogVisible = true
    },
    // 递归得到三级权限的id,并保存到defKeys
    getDefKeys(node, arr) {
      // 是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getDefKeys(item, arr))
    },
    setRightsClosed() {
      // 当关闭分配权限按钮清空默认勾选的节点id值
      this.defKeys = []
    },
    async allotRights() {
      // 角色分配权限
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const strId = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: strId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('权限分配失败')
      }
      this.$message.success('更新成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less">
.el-tag {
  margin: 6px;
}
.topBorder {
  border-top: 1px solid #eee;
}
.bottomBorder {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
